package cn.com.generaldata.os.ws.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jsoup.helper.StringUtil;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.pojo.BillboardIndustryReports;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.service.common.AutoPushingService;
import cn.com.generaldata.os.service.common.ReportTypeService;
import cn.com.generaldata.os.util.CommonUtil;
import cn.com.generaldata.os.vo.BillboardIndustryVO;
import cn.com.generaldata.os.vo.BillboardRuleVO;
import cn.com.generaldata.os.vo.ReportVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.RportOfIndustryVO;
import cn.com.generaldata.os.vo.UnitVO;
import cn.com.generaldata.os.vo.UserVO;

@InjectName
@Component
public class AutoPushingWS {

	private static Logger logger = LoggerFactory.getLogger(AutoPushingWS.class);

	@Autowired
	private AutoPushingService autoPushingService;
	@Autowired
	private ReportTypeService reportTypeService;
	@Autowired
	private UnitWS unitWs;
	@Autowired
	private ReportWS reportWs;

	public List<BillboardRuleVO> queryAllBillboardRules(String title) {
		return toVoList(autoPushingService.queryAllBillboardRules(title));
	}

	public int queryBillboardCompletReposts(List<String> bIndustryReports, String users) {
		return autoPushingService.queryBillboardCompletReposts(bIndustryReports, users);

	}

	//2014-10-9已完成上报的企业，未完成上报企业
	@At("/monitor/llistdetail")
	@Ok("jsp:/static/ocean/monitor/detaillist")
	public List<RportOfIndustryVO> queryCompletRepost(@Param("id") String id, HttpServletRequest request) {
		List<String> ids = new ArrayList<String>();
		cn.com.generaldata.os.pojo.BillboardIndustry pBR = autoPushingService.queryAllBillboardIndustry(id);
		if (pBR.getbIndustryReports() != null) {
			for (BillboardIndustryReports billboardIndustryReports : pBR.getbIndustryReports()) {
				ids.add(billboardIndustryReports.getId());
			}
		}
		return this.queryCompletReposts(ids, pBR.getUsers());
	}

	public List<RportOfIndustryVO> queryCompletReposts(List<String> bIndustryReports, String users) {
		return autoPushingService.queryCompletReposts(bIndustryReports, users);

	}

	// 催报过渡

	public List<ReportVO> turnQueryReports(String userId, String bill) {
		List<ReportVO> turnQueryReports = autoPushingService.turnQueryReports(userId, bill);
		return turnQueryReports;
	}

	//public List<BillboardIndustry> queryAllBillboardIndustrys(String title, String content, String unit,
	//		String operatorId) {
	//	return toVoIndustryList(autoPushingService.queryAllBillboardIndustrys(title, content, unit, operatorId));
	//}
	//2014-9-4
	@At("/monitor/list")
	@Ok("jsp:/static/ocean/monitor/listcalls")
	public List<BillboardIndustryVO> queryAllBillboardIndustrys(@Param("title") String title,
			@Param("content") String content, @Param("unit") String unit, HttpSession session,
			HttpServletRequest request) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String operatorId = voUser.getId();

		List<BillboardIndustryVO> bList = toVoIndustryList(autoPushingService.queryAllBillboardIndustrys(title,
				content, unit, operatorId));

		return bList;
	}

	private List<BillboardIndustryVO> toVoIndustryList(List<cn.com.generaldata.os.pojo.BillboardIndustry> pBRs) {
		List<BillboardIndustryVO> industrys = new ArrayList<BillboardIndustryVO>();
		for (cn.com.generaldata.os.pojo.BillboardIndustry pBR : pBRs) {
			industrys.add(toVoBillboardIndustry(pBR));
		}
		return industrys;
	}

	private BillboardIndustryVO toVoBillboardIndustry(cn.com.generaldata.os.pojo.BillboardIndustry pBR) {
		if (pBR != null) {
			List<String> bIndustryReports = new ArrayList<String>();
			if (pBR.getbIndustryReports() != null) {
				for (BillboardIndustryReports billboardIndustryReports : pBR.getbIndustryReports()) {
					bIndustryReports.add(billboardIndustryReports.getId());
				}
			}
			int queryBillboardCompletReposts = queryBillboardCompletReposts(bIndustryReports, pBR.getUsers());
			return new BillboardIndustryVO(pBR.getId(), pBR.getOperator().getId(), pBR.getBillboardTitle(),
					pBR.getBillboardContent(), pBR.getIndustryId(), new Byte(pBR.getDateType()).intValue(),
					pBR.getOffset(), pBR.getStatus(), pBR.getLastReadTime(), pBR.getReportSum(), pBR.getUsers(),
					pBR.getUserSum(), bIndustryReports, queryBillboardCompletReposts);
		}
		return null;
	}

	public String createBillboardRule(BillboardRuleVO rule) {
		return autoPushingService.createBillboardRule(toPojo(rule));
	}

	//public void removeBillboardIndustry(List<String> ids) {
	//	for (String id : ids) {
	//		autoPushingService.removeBillboardRule(id);
	//	}
	//}
	//2014-9-9
	@At("/monitor/delpush")
	@Ok("json")
	public Map<String, String> removeBillboardIndustry(@Param("ids") String ids, @Param("title") String title,
			@Param("content") String content, @Param("unit") String unit, HttpSession session,
			HttpServletRequest request) {
		String[] id = ids.split(",");
		for (String delId : id) {
			if (delId.trim().length() == 0) {
				continue;
			}
			autoPushingService.removeBillboardRule(delId);
		}
		return CommonUtil.createOKMsg("删除成功");
	}

	//2014-9-29
	@At("/monitor/listdetail")
	@Ok("jsp:/static/ocean/monitor/detailist")
	public ResultVO<UnitVO> getQyList(@Param("id") String id, HttpServletRequest request) {
		String ids = "";
		cn.com.generaldata.os.pojo.BillboardIndustry pBR = autoPushingService.queryAllBillboardIndustry(id);
		if (pBR.getbIndustryReports() != null) {
			for (BillboardIndustryReports billboardIndustryReports : pBR.getbIndustryReports()) {
				ids = ids + billboardIndustryReports.getId() + ",";
			}
		}

		return unitWs.queryUnitByIds(ids, 1);
	}

	//2014-10-20
	@At("/monitor/saveCb")
	public String createBillboardIndustrys(@Param("title") String title, @Param("users") String users,
			@Param("ids") String ids, @Param("sysValue") String sysValue, @Param("xlValue") String xlValue,
			@Param("date") String reportDate, @Param("dday") int dday, HttpServletRequest request, HttpSession session) {
		// 获取报表时段时间
		String timeDate = "";
		String quarterDate = "";
		if (!StringUtil.isBlank(reportDate)) {
			String[] split = reportDate.split("-");
			timeDate = reportDate.replace("-", "/");
			String month = split[1];
			if (Integer.valueOf(month) <= 3)
				quarterDate = "1";
			else if (Integer.valueOf(month) <= 6 && Integer.valueOf(month) > 3) {
				quarterDate = "2";
			} else if (Integer.valueOf(month) <= 9 && Integer.valueOf(month) > 6) {
				quarterDate = "3";
			} else if (Integer.valueOf(month) <= 12 && Integer.valueOf(month) > 9) {
				quarterDate = "4";
			}
		}
		BillboardIndustryVO bIndustry = new BillboardIndustryVO();
		String sysVal = "";
		List<SystemCodedic> sysList = reportWs.queryType();
		for (SystemCodedic statSystem : sysList) {
			if (sysValue.equals(statSystem.getCode())) {
				sysVal = statSystem.getCodeName();
				break;
			}
		}
		bIndustry.setBillboardTitle(title.trim());

		String content = "请尽快提交以下报表：\n";

		List<cn.com.generaldata.os.newpojo.ReportType> cbReportTypes = new ArrayList<cn.com.generaldata.os.newpojo.ReportType>();
		String repIds[] = ids.split(",");
		for (String repId : repIds) {
			if (!"".equals(repId)) {
				cn.com.generaldata.os.newpojo.ReportType cbRepType = reportTypeService.getReportTypeById(repId);
				//季报
				if ("2".equals(cbRepType.getTypeTime()))
					cbRepType.setTypeMeasureUnit(timeDate + "-" + quarterDate);
				else
					cbRepType.setTypeMeasureUnit(timeDate);
				content += "《" + sysVal + " 报表制度中的：" + cbRepType.getTypeName() + "》\n";
				cbReportTypes.add(cbRepType);
			}
		}

		bIndustry.setBillboardContent(content);
		UserVO user = (UserVO) session.getAttribute("user");
		bIndustry.setOperatorId(user.getId());
		bIndustry.setIndustryId(xlValue);
		bIndustry.setReportEnd(Integer.valueOf(dday));
		bIndustry.setStatus("UNREAD");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date time = null;
		try {
			time = sdf.parse(sdf.format(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		bIndustry.setLastReadTime(time);
		return this.createBillboardIndustry(bIndustry, cbReportTypes, users);
	}

	public String createBillboardIndustry(BillboardIndustryVO bIndustry,
			List<cn.com.generaldata.os.newpojo.ReportType> cbReportTypes, String users) {
		return autoPushingService.createBillboardIndustry(toPojoBIndustry(bIndustry), cbReportTypes, users,
				bIndustry.getReportEnd());
	}

	private cn.com.generaldata.os.pojo.BillboardIndustry toPojoBIndustry(BillboardIndustryVO bi) {
		User operator = new User();
		operator.setId(bi.getOperatorId());

		return new cn.com.generaldata.os.pojo.BillboardIndustry(bi.getId(), operator, bi.getBillboardTitle(),
				bi.getBillboardContent(), bi.getIndustryId(), new Integer(bi.getDateType()).byteValue(),
				bi.getOffset(), bi.getStatus(), bi.getLastReadTime(), bi.getReportSum(), bi.getUsers(), bi.getUserSum());
	}

	public void removeBillboardRule(String id) {
		autoPushingService.removeBillboardRule(id);
	}

	private BillboardRuleVO toVo(cn.com.generaldata.os.pojo.BillboardRule pBR) {
		return new BillboardRuleVO(pBR.getId(), pBR.getOperator().getId(), pBR.getBillboardTitle(),
				pBR.getBillboardContent(), Arrays.asList(pBR.getUserIds().split(",")),
				new Byte(pBR.getDateType()).intValue(), pBR.getOffset());
	}

	private List<BillboardRuleVO> toVoList(List<cn.com.generaldata.os.pojo.BillboardRule> pBRs) {
		List<BillboardRuleVO> rules = new ArrayList<BillboardRuleVO>();
		for (cn.com.generaldata.os.pojo.BillboardRule pBR : pBRs) {
			rules.add(toVo(pBR));
		}
		for (int i = 0; i < rules.size(); i++) {
			rules.get(i).setUserIds(null);
		}
		return rules;
	}

	private cn.com.generaldata.os.pojo.BillboardRule toPojo(BillboardRuleVO br) {
		User operator = new User();
		operator.setId(br.getOperatorId());

		return new cn.com.generaldata.os.pojo.BillboardRule(br.getId(), operator, br.getBillboardTitle(),
				br.getBillboardContent(), br.getUserIds().toString().replaceAll("\\[", "").replaceAll("\\]", ""),
				new Integer(br.getDateType()).byteValue(), br.getOffset());
	}

	public void setAutoPushingService(AutoPushingService autoPushingService) {
		this.autoPushingService = autoPushingService;
	}

}
